import TextEditor from '@/pages/cues/components/TextEditor';
import UploadDragger from '@/pages/cues/components/UploadDragger';
import { saveNeeds } from '@/services/api/api-needs';
import { CheckCircleTwoTone, SendOutlined } from '@ant-design/icons';
import {
  DrawerForm,
  ModalForm,
  ProForm,
  ProFormDateRangePicker,
  ProFormInstance,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, message } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import { DefaultOptionType } from 'antd/es/select';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import moment from 'moment';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';

interface DetailApprovalProps {
  onRefurbish: () => void;
}

const DetailApproval: React.FC<DetailApprovalProps> = ({ onRefurbish, triggerMode }) => {
  const access = useAccess();
  const { initialState, setInitialState } = useModel('@@initialState');

  const formRef = useRef<ProFormInstance>();

  const [openAddActive, setOpenAddActive] = useState<boolean>();

  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  /**
   * 级联组件 搜索筛选
   * @param inputValue
   * @param path
   * @returns
   */
  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  return (
    <DrawerForm
      key="drawer_form_add_approval"
      title="批示"
      drawerProps={{
        destroyOnClose: true,
        width: 800,
        maskClosable: false,
      }}
      formRef={formRef}
      trigger={<a>批示</a>}
      initialValues={{
        initiateOrganization: initialState?.currentUser?.organizationName,
      }}
      open={openAddActive}
      onOpenChange={(visible) => {
        setOpenAddActive(visible);
        if (visible) {
          loadInitMediaOrganization();
        } else {
        }
      }}
      layout="horizontal"
      submitter={{
        render: (props, defaultDoms) => {
          return [
            <Button onClick={() => setOpenAddActive(false)}>取消</Button>,
            <Button
              key="button_add_submit"
              icon={<SendOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              onClick={() => {
                /**
                 * ======================
                 * 直接发布
                 * ======================
                 */
                const values = formRef.current?.getFieldsValue();

                setModalFormOpenState(true);
              }}
            >
              提交
            </Button>,
            <ModalForm
              key={'modal_form_add_submit'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  确认提交
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: 400,
                destroyOnClose: true,
              }}
              open={modalFormOpen}
              onOpenChange={setModalFormOpenState}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async () => {
                const values = formRef.current?.getFieldsValue();

                if (
                  values.articleAttachments !== undefined &&
                  values.articleAttachments.length > 0
                ) {
                  const articleAttachments = values.articleAttachments.map(
                    (item: { response: { data: { id: any } } }) => {
                      return item.response.data.id;
                    },
                  );

                  values.attachmentIds = articleAttachments;
                }
                console.log(values);
                values.deadlineTime = moment(values.deadlineTime).format('YYYY-MM-DD HH:mm:ss');
                const response = await saveNeeds({
                  ...values,
                  createdSource: 1,
                });

                if (response.code === 0) {
                  message.success('提交成功');
                  setOpenAddActive(false);
                  onRefurbish();
                  return true;
                } else {
                  return false;
                }
              }}
            />,
          ];
        },
      }}
    >
      <ProFormTextArea
        width="xl"
        name="content"
        label="请示"
        required={true}
        fieldProps={{
          allowClear: true,
          maxLength: 200,
        }}
      />

      <ProFormDateRangePicker
        name="interviewTime"
        label="采访时间"
        allowClear
        required={true}
        width="xl"
        fieldProps={{
          allowClear: true,
          format: 'YYYY-MM-DD',
          disabledDate: (current) => {
            return current && current < dayjs().endOf('day');
          },
        }}
        extra="需求方期望的采访开始时间与结束时间"
      />

      <ProFormTextArea
        width="xl"
        name="location"
        label="采访地点"
        required={true}
        fieldProps={{
          allowClear: true,
          maxLength: 200,
        }}
      />

      <ProForm.Item name="content" required={true} label="采访内容">
        <TextEditor
          onInit={(editor) => {}}
          readonly={false}
          onClick={(value) => {}}
          defaultContent=""
          tinyID="tinyId"
        />
      </ProForm.Item>
      <FormItem
        name="articleAttachments"
        label={
          <span
            style={{
              marginLeft: 11,
            }}
          >
            附件
          </span>
        }
      >
        <UploadDragger
          style={{
            marginLeft: '28px',
          }}
          onPreview={(file) => {}}
          access={{
            isPicture: access.主动报送x报送线索x附件x图片,
            isVideo: access.主动报送x报送线索x附件x视频,
            isOffice: access.主动报送x报送线索x附件x办公,
            isOther: access.主动报送x报送线索x附件x其他,
          }}
          url="/cues/interview/attachment/save"
          mode="interview"
        />
      </FormItem>
    </DrawerForm>
  );
};
export default DetailApproval;
